package cmdUtil

import (
	"CmdUtil/config"
	"fmt"
	"github.com/ThomasRooney/gexpect"
	"log"
	"sync"
	"time"
)

func Run(cfg config.Config) {
	fmt.Println()
	log.Println("执行命令: ", cfg.Cmd)
	var wg sync.WaitGroup
	child, err := gexpect.SpawnAtDirectory(cfg.Cmd, cfg.WorkDir)
	if err != nil {
		log.Fatal(err)
	}
	for k, v := range cfg.Input {
		wg.Add(1)
		go func(input, value string) {
			defer wg.Done()
			err = child.ExpectTimeout(input, time.Second*20)
			if err != nil {
				log.Println(input, err)
			} else {
				err = child.SendLine(value)
				if err != nil {
					log.Println(err)
				}
				child.Interact()
				_ = child.Wait()
			}
		}(k, v)
	}
	wg.Wait()
	fmt.Println()
	log.Println("命令执行完成")
}
